package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"newapp/dao"
	"newapp/middleware"
	"newapp/model"
	"newapp/tool"
)

type MemberController struct {
}

func (mc *MemberController) Register(engine *gin.Engine) {
	engine.POST("/user/register", mc.register)
	engine.POST("/user/login", mc.login)
	engine.GET("/user/info",middleware.UserMiddleware(), mc.info )

}

func (mc *MemberController) register(ctx *gin.Context) {
	//获取数据
	db := tool.GetDB()
	var user model.User
	err := ctx.ShouldBind(&user)
	if err != nil {
		return
	}
	fmt.Println(user.UserName)
	fmt.Println(user.PassWord)
	fmt.Println(user.Phone)
	//数据验证
	if len(user.PassWord) < 6 {
		ctx.JSON(http.StatusUnprocessableEntity, map[string]interface{}{
			"code": 422,
			"msg":  "密码不得小于6位",
		})
		return
	}
	if len(user.Phone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "手机号必须是11位",
		})
		return
	}
	if len(user.UserName) == 0 {
		user.UserName = tool.RandomString(10)
	}
	log.Println(user.UserName, user.PassWord, user.Phone)
	//判断手机号是否存在
	if dao.DaoUser(db, user.Phone) {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "手机号已经注册过，请登录",
		})
	}

	//创建用户

	err = dao.CreateUserDao(db, user)
	if err != nil {
		ctx.JSON(500, gin.H{
			"code": "500",
			"msg":  "密码加密出现问题",
		})
	}
	//ctx.JSON(http.StatusOK, gin.H{
	//	"code":200,
	//	"msg":"注册成功",
	//})
	//返回结果
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "创建成功~",
	})
}

func (mc *MemberController) login(context *gin.Context) {
	//获取数据
	db := tool.GetDB()
	var user model.User
	err := context.ShouldBind(&user)
	if err != nil {
		return
	}

	//数据验证
	if !dao.IsCorrectDao(db, user) {
		context.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 422,
			"msg":  "账号or密码不正确",
		})
		return
	}
	//发放token
	token, err:= tool.ReleaseToken(user)
	if err!=nil{
		context.JSON(http.StatusInternalServerError, gin.H{
			"code":500,
			"msg":"系统异常",
		})
		log.Printf("token generate error: %v", err)
		return
	}


	//返回结果
	context.JSON(http.StatusOK, gin.H{
		"code": 200,
		"data": gin.H{"token": token},
		"msg":  "登录成功",
	})
}

func (mc *MemberController) info(context *gin.Context) {
	user, _ := context.Get("user")
	context.JSON(http.StatusOK,gin.H{
		"code":200,
		"data":gin.H{
			"user":user,
		},
	})
}
